package hu.myai.util;

import java.io.File;
import java.io.PrintStream;
import java.net.Socket;

import org.joone.log.ILogger;
import org.joone.log.LoggerFactory;

public class MailUtil {

	private static final ILogger log = LoggerFactory.getLogger(MailUtil.class);

	public MailUtil() {
	}

	public void sendMail(String to, String host, String body, String file) {
		try {
			Socket sock;
			PrintStream ps;

			sock = new Socket(host, 25);
			ps = new PrintStream(sock.getOutputStream());

			MIMEBase64 mimeBase64 = new MIMEBase64();

			body = body.replaceAll("\\\\t", "\t");
			body = body.replaceAll("\\\\n", "\r\n");
			ps.println("mail from: myai");
			ps.println("rcpt to: " + to);
			ps.println("data");
			ps.println("MIME-Version: 1.0");
			ps.println("subject: ASX suggestion");
			ps.println("Content-Type: multipart/mixed; boundary=\"DATASEPARATOR\";");
			ps.println("--DATASEPARATOR");
			ps.println("Content-Type: text/plain; charset=\"us-ascii\"");
			ps.println(body);
			ps.println("--DATASEPARATOR");

			if (file != null) {
				String fileName = new File(file).getName();

				ps.println("Content-Type:application/octet-stream; name=" + fileName);
				ps.println("Content-Disposition: attachment;filename=\"" + fileName + "\"");
				ps.println("Content-transfer-encoding: base64");
				ps.println(mimeBase64.encode(file));
				ps.println("--DATASEPARATOR");
			}
			ps.println("\r\n--DATASEPARATOR--");
			ps.println(".");

			ps.flush();
			sock.close();

		} catch (Exception e) { // Handle any exceptions, print error message.
			log.error("Error - Mail was not sent: " + e.getMessage());
		}
	}
}
